package com.sunpy.commonlock.quartz;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class QuartzServiceImpl implements IQuartzService {

    private static final String JOB_GROUP_NAME = "DEFAULT_JOB_GROUP";
    private static final String TRIGGER_GROUP_NAME = "DEFAULT_TRIGGER_GROUP";
    @Autowired
    private Scheduler scheduler;

    @Override
    public void doScheduleJob(String jobName, Class<? extends Job> cls,
                              String cron, Map<String, Object> paramMap) {
        try {
            JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, JOB_GROUP_NAME).build();

            paramMap.forEach((key, value) -> {
                jobDetail.getJobDataMap().put(key, value);
            });

            CronTrigger trigger = (CronTrigger) TriggerBuilder
                    .newTrigger()
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteJob(String jobName) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME);
        JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
        try {
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateJob(String jobName, Class<? extends Job> cls,
                          String cron, Map<String, Object> paramMap) {
        this.deleteJob(jobName);
        this.doScheduleJob(jobName, cls, cron, paramMap);
    }

    @Override
    public JobDetail getDetail(String jobName, Class<? extends Job> cls) {
        JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(jobName, JOB_GROUP_NAME).build();
        return jobDetail;
    }
}
